package com.mediacloud.app.newsmodule.activity;


import static com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig.getAppServerConfigInfo;

import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentTransaction;

import com.chinamcloud.collect.AcquisitionManager;
import com.eventTrack.CDPTrackReportManager;
import com.mediacloud.app.appfactory.cache.UserRecommend;
import com.mediacloud.app.assembly.util.ImageKitKt;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleItemReciver;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.IntegralConfig;
import com.mediacloud.app.model.news.ReadDataReciver;
import com.mediacloud.app.model.news.ShowSwitch;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.broadcast.PowerStateReciver;
import com.mediacloud.app.newsmodule.fragment.NotifyMicroEvent;
import com.mediacloud.app.newsmodule.fragment.video.vod.VideoVodDetailFragment;
import com.mediacloud.app.newsmodule.utils.AddIntegralCounter;
import com.mediacloud.app.newsmodule.utils.AddMedalStatistics;
import com.mediacloud.app.newsmodule.utils.Addintegral;
import com.mediacloud.app.newsmodule.utils.DisplayCutoutManager;
import com.mediacloud.app.newsmodule.utils.DomainUtil;
import com.mediacloud.app.newsmodule.utils.KillMusicUtils;
import com.mediacloud.app.newsmodule.utils.ReadStatusInvoker;
import com.mediacloud.app.newsmodule.utils.VideoAddressGet;
import com.mediacloud.app.newsmodule.utils.share.ShareWrap;
import com.mediacloud.app.reslib.analysis.AnalysisUtils;
import com.mediacloud.app.reslib.config.NewsDetailStyleConfig;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.enums.ListStyle;
import com.mediacloud.app.reslib.enums.TitileType;
import com.mediacloud.app.reslib.enums.XKey;
import com.mediacloud.app.reslib.util.DataInvokeUtil;
import com.mediacloud.app.user.model.UserInfo;
import com.tencent.mmkv.MMKV;
import com.utils.ClickUtils;
import com.utils.NetUtils;
import com.utils.UriTool;
import com.yoake.media.player.XPlayer;
import com.yoake.media.player.utils.OnPlayerActionListener;
import com.yoake.media.player.utils.XVideoBitRate;
import com.yoake.media.player.utils.XVideoItem;
import com.yoake.media.player.utils.XVideoSpeed;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Response;
import xyz.doikki.videoplayer.player.VideoView;


/**
 * 视频直播
 */
public class VideoVodVRDetailActivity extends StyleSetActivity  {
    protected boolean isAutoPlay;
    public XPlayer vrPlayer;

    protected Handler handler = new RecommendClickHandle();
    VideoVodDetailFragment fragment;
    boolean isOutView = false;
    PowerStateReciver powerStateReciver;
    ShowSwitch showSwitch;
    //支付相关

    LinearLayout broccoliLayout;
    View vodBottomContent;
    private View rlayout_back;
    public ShareWrap shareWrap;//播放器更多
    long  mTyReportStartTime=0;
    long  mTyReportEndTime=0;

    @Override
    public boolean showTitleBar() {
        return false;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isCommentDialog=true;
        super.onCreate(savedInstanceState);

        Uri uriData = getIntent().getData();
        if (uriData != null) {
            isFromH5OpenToReStart =UriTool.INSTANCE.isFromH5OpenToReStart(this,uriData);
            String articleid = uriData.getQueryParameter("articleid");
            String title = uriData.getQueryParameter("title");
            String cname = uriData.getQueryParameter("cname");
            String tag = uriData.getQueryParameter("tag");
            catalogItem = new CatalogItem();
            catalogItem.setCatname(cname);
            articleItem = new ArticleItem();
            try {
//                articleItem.setTitle(title);
                articleItem.setId(Long.valueOf(articleid));
            } catch (Exception e) {
            }
        } else {
            catalogItem = getIntent().getParcelableExtra("catalog");
            articleItem = getIntent().getParcelableExtra("data");
            if (articleItem == null) {
                articleItem = ArticleItem.praseIntentDataToArticleItem(getIntent(), TypeX.NEWS.VIDEO);
            }
        }
        if (articleItem != null) {
            readStatus();
            showSwitch = articleItem.getmShowSwitch();
        }
        if (catalogItem == null) {
            catalogItem = new CatalogItem();
        }
        rlayout_back=findViewById(R.id.rlayout_back);
        loadingView = findViewById(R.id.mLoadingView);
        initStateView();
        if (retryTips!=null){
            retryTips.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ClickUtils.delayClickable(v);
                    if (hasNetWork){
                        if (currentState != TYPE_LOADING) {
                            showStateView(TYPE_LOADING, false);
                            getVideoDetail();
                        }
                    }else{
                        showNetWorDialog();
                    }
                }
            });
        }
        if (rlayout_back!=null){
            rlayout_back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ClickUtils.delayClickable(v);
                    finish();
                }
            });
        }
        if (loadingView!=null) {
            loadingView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ClickUtils.delayClickable(v);
                    if (hasNetWork){
                        if (currentState != TYPE_LOADING) {
                            showStateView(TYPE_LOADING, false);
                            getVideoDetail();
                        }
                    }else{
                        showNetWorDialog();
                    }


                }
            });
        }
        vodBottomContent = Utility.findViewById(mRootView, R.id.vodBottomContent);
        broccoliLayout = Utility.findViewById(mRootView, R.id.broccoliLayout);
        boolean isLeftImgMode = ListStyle.TotoalStyle.LEFT_IMAGE.equals(serverAppConfigInfo.getContent_list());
        if (isLeftImgMode) {
            for (int i = 0; i < 3; i++) {
                broccoliLayout.addView(LayoutInflater.from(this).inflate(R.layout.layout_broccoli21, null));
            }
        } else {
            for (int i = 0; i < 3; i++) {
                broccoliLayout.addView(LayoutInflater.from(this).inflate(R.layout.layout_broccoli22, null));
            }
        }
        vrPlayer = Utility.findViewById(mRootView, R.id.vrPlayer);
        vrPlayer.setRelease(false);
        vrPlayer.getPrepareView().setVisibleThumb(false);
        vrPlayer.getCompleteView().setVisibleThumb(false);
        vrPlayer.setPoster(ImageKitKt.buildUrl(3,articleItem.getLogo()), ContextCompat.getDrawable(this, R.drawable.cctv7_loading_img));
        vrPlayer.setPendingSeek(VideoSeekKit.getHisSeek("" + articleItem.getId()));
        ViewGroup.LayoutParams lp = vrPlayer.getLayoutParams();
        lp.height = (int) (9f * Utility.getScreenWidth(this) / 16);
        vrPlayer.setLayoutParams(lp);
        getLifecycle().addObserver(vrPlayer);

        isAutoPlay = MMKV.defaultMMKV().decodeBool(XKey.AUTO_PLAY, false);
        vrPlayer.setAutoPlay(isAutoPlay);
        if (articleItem == null)
            return;
        fragment = new VideoVodDetailFragment();

        tvLetmeSay.setText("我来说几句");
        vrPlayer.getController().getControllerInstance().setEnableOrientation(true);
        KillMusicUtils.stopAPS(this);
        LinkedHashSet<String> linkedHashSet = getAppServerConfigInfo(this).getNewsDetailConfig().getLinkedHashSet();
        if(!linkedHashSet.contains(NewsDetailStyleConfig.COLLECT_BUTTON) && !linkedHashSet.contains(NewsDetailStyleConfig.SHARE_BUTTON)){
            vrPlayer.getTitleView().hideTitleMoreView();
            vrPlayer.getErrorView().hideTitleMoreView();
        }
        vrPlayer.setOnTitleMoreClickListener((it) ->
                {
                    ClickUtils.delayClickable(it);
                    try {
                        if(vrPlayer.isFullScreen()){
                            vrPlayer.getController().getControllerInstance().hide();
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    shareWrap = new ShareWrap(this,false);
                    shareWrap.setShowFunction(true);
                    shareWrap.init(articleItem,new CatalogItem());
                    shareWrap.show(mRootView);
                });
        getVideoDetail();


        powerStateReciver = new PowerStateReciver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_POWER_CONNECTED);
        intentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        registerReceiver(powerStateReciver, intentFilter);
        setNewsTitle();


        onPageStart();
        showPageTransition();
        //设置使用刘海屏幕区域
        new DisplayCutoutManager(this).set(WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES);
//        vrPlayer.setScreenListener(new VRFullScreenListener() {
//            @Override
//            public void onScreenChange(boolean b) {
//                if(b){
//                    WindowManager.LayoutParams windowLP = getWindow().getAttributes();
//                    windowLP.alpha = 1f;
//                    getWindow().setAttributes(windowLP);
//                }else{
//                    WindowManager.LayoutParams windowLP = getWindow().getAttributes();
//                    windowLP.alpha = 0f;
//                    getWindow().setAttributes(windowLP);
//                }
//            }
//        });
        swipeBackLayout.setSupportSwipe(false);

        judgeInteval();

        if (!NetUtils.isNetConnection(this)) {
            ArticleItemReciver articleItemReciver = new ArticleItemReciver();
            articleItemReciver.articleItem = articleItem;
            if (hadAdded) {
                fragment.setArticleItem(articleItem);
            }
            initDetailFragment(articleItemReciver, true);
            hiddBroccoliLayout();
            setVideoContent(articleItem.getVideo());
        }

    }

    IntegralConfig config;
    boolean openInteval = false;//是否开启积分任务
    boolean openGrow = false;//是否开启成长值任务
    int timeInteval = 0;//增加积分时间（分）
    int timeGrow = 0;//增加成长值时间（分）

    //判断是否开启积分和无和成长任务
    private void judgeInteval() {
        config = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.integralConfig;
        if (config!=null){
            if (config.enableList1!=null && config.enableList1.size()!=0){
                for (int i = 0; i < config.enableList1.size(); i++) {
                    if (config.enableList1.get(i)==8){
                        openInteval = true;
                        timeInteval = config.videoLeastDuration1;
                    }
                }
            }

            if (config.enableList4!=null && config.enableList4.size()!=0){
                for (int i = 0; i < config.enableList4.size(); i++) {
                    if (config.enableList4.get(i)==8){
                        openGrow = true;
                        timeGrow = config.videoLeastDuration4;
                    }
                }
            }
        }
    }


    public ArticleItem getArticleItem() {
        return articleItem;
    }

    @Override
    protected boolean getFitSystemWindow() {
        return true;
    }


    protected void setNewsTitle() {
        int base = serverAppConfigInfo.getBase();
        if (base == TitileType.FRAME) {
            setFrameTypeTitle();
        } else if (base == TitileType.NAVIGATE) {
            setTitle(catalogItem != null ? catalogItem.getCatname() : "");
        } else if (base == TitileType.NEWS_TITLE) {
            setTitle(articleItem != null ? articleItem.getTitle() : "");
        } else if (base == TitileType.NOTITLE) {
            setTitle("");
        }

    }

    Object mark = System.currentTimeMillis();




    @Override
    public void onBackPressed() {
        if (shareWrap!=null&&shareWrap.isShowing()) {
            shareWrap.dismiss();
            isOutView = false;
        }
        if (vrPlayer!=null&&
                vrPlayer.isFullScreen()) {
            vrPlayer.onBackPressed();
        } else {
            finish();
        }

    }


    @Override
    public void finish() {
        super.finish();
        if (articleItem!=null&&mTyReportStartTime>0) {
            mTyReportEndTime=System.currentTimeMillis();
        }
        if (readStatusInvoker != null)
            readStatusInvoker.destory();
        readStatusInvoker = null;

        saveViewHistory();


        try {
            unregisterReceiver(powerStateReciver);
            if (fragment != null) {
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.remove(fragment);
                transaction.commitNowAllowingStateLoss();
            }
        } catch (Exception ex) {
        }
        if (vrPlayer!=null){
            vrPlayer.release();
        }
    }

    @Override
    public int getStatusBarColor() {
        if (vrPlayer != null && vrPlayer.isFullScreen())
            return Color.TRANSPARENT;
        return Color.BLACK;
    }

    @Override
    public int getLayoutResID() {
        return R.layout.aappfactory_activity_videovod_vr_detail;
    }


    protected class RecommendClickHandle extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //分享
            if (msg.what == 0) {
                return;
            }
            //点赞
            else if (msg.what == 100) {
                fragment.setVideoReades(msg.arg1);
            }
            try {
                ArticleItem articleItem = (ArticleItem) msg.obj;
                if (articleItem == null) return;
                if (articleItem.getId() == articleItem.getId())
                    return;
                vrPlayer.setAutoPlay(true);
                saveViewHistory();
                getVideoDetail();
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, "" + e.getMessage());
            }
        }
    }


    protected void deleteHistoryPosition() {
        VideoSeekKit.clearHisSeek("" + articleItem.getId());
    }

    public void saveViewHistory() {
        if (!vrPlayer.isPlaying()) {
            deleteHistoryPosition();
        } else if (vrPlayer.getCurrentPosition() > 0 && vrPlayer.getCurrentPosition() < vrPlayer.getDuration()) {
            addViewHistory(vrPlayer.getCurrentPosition());
        }
    }

    protected void addViewHistory(long position) {
        VideoSeekKit.addHisSeek("" + articleItem.getId(),position);
    }

    public String mp4Data;


    public void success(ArticleItemReciver data) {
        if (isFinishing()||isDestroyed()){
            return;
        }

        if (data.state && data.articleItem != null) {
            articleItem = data.articleItem;
            sendExposureEvent();
            refreshBottomStyle(data.articleItem, 1);
            UserRecommend.addItemKeyWord(articleItem, this);
            articleItem.mShowSwitch = showSwitch;
            if (hadAdded) {
                fragment.setArticleItem(articleItem);
            }

            initDetailFragment(data, true);
            //  vrPlayer.getPoster().load(articleItem.getLogo(),AppFactoryGlobalConfig.getDefaultImageLoadDrawable(),0);
            setVideoContent(articleItem.getVideo());
        }
        AddMedalStatistics.addMedalStatistics(this);//勋章统计
        startAddIntegralCounter();
    }

    private void startAddIntegralCounter() {
        AddIntegralCounter.start(this, new AddIntegralCounter.TimeoutCallback() {
            @Override
            public void timeoutCallback() {
                if (articleItem == null) {
                    return;
                }
//                Addintegral.addintegral(VideoVodVRDetailActivity.this, articleItem.getId(), 2, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0",articleItem);
            }
        });

        //开启视频任务时
        if (openInteval){
            AddIntegralCounter.start(this, new AddIntegralCounter.TimeoutCallback() {
                @Override
                public void timeoutCallback() {
                    if (articleItem == null) {
                        return;
                    }
                    Addintegral.addintegral(VideoVodVRDetailActivity.this, articleItem.getId(), 8, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0",openGrow,articleItem);
                }
            }, Math.min(timeInteval,timeGrow),AddIntegralCounter.VideoTask);
        }

    }

    public void hiddBroccoliLayout() {
        if (rlayout_back!=null){
            rlayout_back.setVisibility(View.GONE);
        }
        broccoliLayout.setVisibility(View.GONE);
        closeStateView();

    }

    private void setVideoContent(String videoStr) {
        try {
            JSONObject video = new JSONObject(videoStr);
            String cdn = video.optString("cdnConfigEncrypt");
            String poster = video.optString("poster", "");
            JSONArray tsAddress = VideoAddressGet.getAddress(video);
            if (tsAddress != null) mp4Data = tsAddress.toString();
//            VideoPlayObj videoPlayObj = new VideoPlayObj();
//            videoPlayObj.setTitle(articleItem.getTitle());
//            videoPlayObj.setVID(articleItem.getVid());
//            videoPlayObj.setCdn_iv(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv);
//            videoPlayObj.setCdn_key(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key);

            XVideoItem videoItem = new XVideoItem(articleItem.getTitle());

            for (int i = 0; tsAddress != null && i < tsAddress.length(); i++) {
                JSONObject line = tsAddress.optJSONObject(i);
                String url = line.optString("url");
                String title = line.optString("title");
                if (!TextUtils.isEmpty(url)) {
                    videoItem.getBitRates().add(new XVideoBitRate(title, url, null));
                }

            }
            vrPlayer.addVideoItemReverse(videoItem, "源码", true);
            if (videoItem.getBitRates().size() > 0) {
                setVideoPlayerData();
            } else {
//                vrPlayer.onExternalError();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "" + e.getMessage());

        }
    }

    boolean hadAdded = false;

    public void setVideoPlayerData() {
        vrPlayer.addOnStateChangeListener(new VideoView.OnStateChangeListener() {
            @Override
            public void onPlayerStateChanged(int playerState) {
                if(playerState == VideoView.STATE_PAUSED){

                }
            }

            @Override
            public void onPlayStateChanged(int playState) {
                if (playState == VideoView.STATE_PAUSED) {

                } else if (playState == VideoView.STATE_PLAYBACK_COMPLETED) {

                    if (!isFinish) {
                        deleteHistoryPosition();
                    }
                } else if (playState == VideoView.STATE_PLAYING) {

                }else if (playState == VideoView.STATE_ERROR){

                }
            }
        });

        vrPlayer.setOnPlayerActionListener(new OnPlayerActionListener() {
            @Override
            public void onProjectionScreen() {
                //投屏回调
            }

            @Override
            public void onSpeedChange(@Nullable XVideoSpeed before, @NonNull XVideoSpeed after) {

            }

            @Override
            public void onBitRateChange(@Nullable XVideoBitRate before, @NonNull XVideoBitRate after) {

            }

            @Override
            public void onDamuSwitch(boolean isOpen) {
                if (isOpen){

                }else{

                }
            }

            @Override
            public void onPlayerStateChanged(int playerState) {
                boolean isFullScreen = playerState == VideoView.PLAYER_FULL_SCREEN;
                if (isFullScreen){

                }else {

                }

            }

            @Override
            public void onSeekTo(boolean isForward) {
                if (isForward){

                }else{

                }
            }
        });
    }



    protected void initDetailFragment(ArticleItemReciver data, boolean appfacBuy) {
        if (hadAdded)
            return;
        Bundle args = new Bundle();
        //ArticleItem nItem = ArticleItem.parse(data.articleItem.orginDataObject);
        //   nItem.setContent(null);
        args.putParcelable("data", data.articleItem);
        args.putParcelable("catalog", catalogItem);
        args.putBoolean("appfacBuy", appfacBuy);
        args.putParcelableArrayList("components", data.components);
        fragment.setArguments(args);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.vodBottomContent, fragment);
        transaction.show(fragment);
        transaction.commitAllowingStateLoss();
        hadAdded = true;
    }




    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

    }

    ReadStatusInvoker readStatusInvoker;

    public void readStatus() {
        readStatusInvoker = new ReadStatusInvoker(new DataInvokeCallBack<ReadDataReciver>() {
            @Override
            public void success(ReadDataReciver data) {
                AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, data.virtualIncrement);
                Message msg = new Message();
                msg.what = 100;
                msg.arg1 = (int) data.reads;
                handler.sendMessageDelayed(msg, 2000);
            }

            @Override
            public void fault(Object data) {
                AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, AnalysisUtils.DefaultVirtualIncrement);
            }
        });
        readStatusInvoker.readStatistics(articleItem.getId() + "", 1);
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (articleItem != null) {
            UserInfo info = UserInfo.getUserInfo(this);
            AcquisitionManager.getInstance().readEnter(info, "" + articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (articleItem != null) {
            UserInfo info = UserInfo.getUserInfo(this);
            AcquisitionManager.getInstance().readExit(info, "" + articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }


    @Override
    public boolean isShowNetWorDialog() {

        return false;
    }

    @Override
    public void noNetwork() {
//        showStateView(TYPE_NET_NOT_GIVE_FORCE,false);
//        if (rlayout_back!=null){
//            rlayout_back.setVisibility(View.VISIBLE);
//        }

    }


    public void getVideoDetail() {
        Map<String, String> map = new HashMap();
        map.put("client", "android");
        CatalogItem catalogItem = getIntent().getParcelableExtra("catalog");
        if (catalogItem == null) {
            catalogItem = new CatalogItem();
            String nid = getIntent().getStringExtra("navigate_id");
            if (nid == null) {
                nid = "";
            }
            catalogItem.setCatid(nid);
        }
        String navigate_id = catalogItem != null ? catalogItem.getCatid() : "";
        if (!TextUtils.isEmpty(navigate_id)) {
            map.put("navigate_id", "navigate_id");
        }
        DataInvokeUtil.ziMeiTiApi
                .getArticleById("" + articleItem.getId(), map)
                .map(new Function<Response<JSONObject>, ArticleItemReciver>() {
                    @Override
                    public ArticleItemReciver apply(Response<JSONObject> jsonObjectResponse) throws Exception {
                        ArticleItemReciver articleItemReciver = new ArticleItemReciver();
                        articleItemReciver.readFromJson(jsonObjectResponse.body());
                        return articleItemReciver;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ArticleItemReciver>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ArticleItemReciver articleItemReciver) {
                        success(articleItemReciver);
                    }

                    @Override
                    public void onError(Throwable e) {
//                        vrPlayer.onExternalError();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CDPTrackReportManager.getInstance().NewsContentDetailView(articleItem,(System.currentTimeMillis() - inTime)/1000);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (vrPlayer != null && !isFinish) {
            if (commentIsOpen) {
                commentIsOpen =false;
                if (vrPlayer.getPlayStateAtLifecycleOwnerPause() == VideoView.STATE_PLAYING
                        ||vrPlayer.getPlayStateAtLifecycleOwnerPause() == VideoView.STATE_PREPARING
                        ||vrPlayer.getPlayStateAtLifecycleOwnerPause() == VideoView.STATE_PREPARED) {
                    vrPlayer.start();
                }
            }
        }

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void restorePause(NotifyMicroEvent event){
        //防止点击home键，评论框pause了，视频也应该pause
        if (vrPlayer != null){
            if (event.getPlay())
                vrPlayer.resume();
            else
                vrPlayer.pause();
        }
    }

}